package http_proxy_middleware

import (
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"gitee.com/zhoulvvv/my_go_gateway/middleware"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"log"
	"strings"
)

// HTTP strip_uri
// 比如请求是：http://127.0.0.1:8881/test_http_new2/dddd
// strip uri 之后是：http://127.0.0.1:8881/dddd
// 就是去掉接入前缀
func HTTPStripUriModeMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		serviceInterface, ok := c.Get("service")
		if !ok {
			middleware.ResponseError(c, 2001, errors.New("【服务不存在】service not found"))
			c.Abort()
			return
		}
		service := serviceInterface.(*dao.ServiceDetail)
		if service.HTTPRule.RuleType == public.HTTPRuleTypePrefix &&
			service.HTTPRule.NeedStripUri == 1 {
			log.Printf("strip uri 中间件替换前：%s", c.Request.URL.Path)
			c.Request.URL.Path = strings.Replace(c.Request.URL.Path,
				service.HTTPRule.Rule, "", 1)
			log.Printf("strip uri 中间件替换后：%s", c.Request.URL.Path)
		}
		c.Next()
	}
}
